package com.ijmacd.footballtracker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.impl.cookie.DateUtils;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MatchViewActivity extends Activity implements OnClickListener, OnTouchListener {
	private static final String TAG = "MatchViewActivity";

    private static final String[] PROJECTION = new String[] {
            Provider.Matches._ID, // 0
            Provider.Matches.DATE, // 1
            Provider.Matches.STATUS, // 2
            Provider.Matches.HOME_TEAM, // 3
            Provider.Matches.AWAY_TEAM, // 4
            Provider.Matches.HOME_TEAM_NAME, // 5
            Provider.Matches.AWAY_TEAM_NAME, // 6
            Provider.Matches.HOME_GOALS, // 7
            Provider.Matches.AWAY_GOALS, // 8
            Provider.Matches.ATTENDANCE, // 9
    };
    private static final int COLUMN_INDEX_DATE = 1;
    private static final int COLUMN_INDEX_STATUS = 2;
    private static final int COLUMN_INDEX_HOME_TEAM = 3;
    private static final int COLUMN_INDEX_AWAY_TEAM = 4;
    private static final int COLUMN_INDEX_HOME_NAME = 5;
    private static final int COLUMN_INDEX_AWAY_NAME = 6;
    private static final int COLUMN_INDEX_HOME_GOALS = 7;
    private static final int COLUMN_INDEX_AWAY_GOALS = 8;
    private static final int COLUMN_INDEX_ATTENDANCE = 9;
    
	private Uri mUri;
	private String mDate;
	private String mHomeUuid;
	private String mAwayUuid;
	private TextView mHomeNameText;
	private TextView mAwayNameText;
	private TextView mHomeGoalsText;
	private TextView mAwayGoalsText;
	private TextView mHomeScorersText;
	private TextView mAwayScorersText;
	private MatchTimeWidget mTimeChrono;
	private TextView mAttendanceText;
	private TextView mDateText;
	private ViewFlipper mExtraFlipper;
	private Cursor mCursor;

	private float flipperX;




	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		
        mUri = getIntent().getData();
		
		setContentView(R.layout.matchview);
		
		mTimeChrono = (MatchTimeWidget)findViewById(R.id.match_time_chr);
		mHomeNameText = (TextView)findViewById(R.id.home_team_txt);
		mAwayNameText = (TextView)findViewById(R.id.away_team_txt);
		mHomeGoalsText = (TextView)findViewById(R.id.home_goals_txt);
		mAwayGoalsText = (TextView)findViewById(R.id.away_goals_txt);
		mHomeScorersText = (TextView)findViewById(R.id.home_scorers_txt);
		mAwayScorersText = (TextView)findViewById(R.id.away_scorers_txt);
		mExtraFlipper = (ViewFlipper)findViewById(R.id.extra_flipper);
		mAttendanceText = (TextView)findViewById(R.id.attendance_txt);
		mDateText = (TextView)findViewById(R.id.date_txt);
		//mAttendanceText = new TextView(this, null, R.style.MatchLabel);
		//mAttendanceText.setTextSize(20);
		//mDateText = new TextView(this, null, R.style.MatchLabel);
		//mDateText.setTextSize(20);
		
		mCursor = managedQuery(mUri, PROJECTION, null, null, Provider.Matches.DEFAULT_SORT_ORDER);

		mHomeNameText.setOnClickListener(this);
		mAwayNameText.setOnClickListener(this);
		mExtraFlipper.setOnTouchListener(this);
		/*Handler handler = null;
		getContentResolver().registerContentObserver(mUri, false, new ContentObserver(handler){

			@Override
			public void onChange(boolean selfChange) {
				super.onChange(selfChange);
			}
			
		});*/
	}
    @Override
	protected void onPause() {
		super.onPause();
		mTimeChrono.stop();
	}
	@Override
    protected void onResume() {
        super.onResume();

        // If we didn't have any trouble retrieving the data, it is now
        // time to get at the stuff.
        if (mCursor != null && mCursor.getCount() > 0) {
            // Make sure we are at the one and only row in the cursor.
            mCursor.moveToFirst();

            mDate = mCursor.getString(COLUMN_INDEX_DATE);
            int status = mCursor.getInt(COLUMN_INDEX_STATUS);
            mTimeChrono.setMatchStart(parseDate(mDate));
            mTimeChrono.setStatus(status);
            if((status & 4) == 0) mTimeChrono.start(); // If not already finished
            mHomeUuid = mCursor.getString(COLUMN_INDEX_HOME_TEAM);
            mAwayUuid = mCursor.getString(COLUMN_INDEX_AWAY_TEAM);
            mHomeNameText.setText(mCursor.getString(COLUMN_INDEX_HOME_NAME));
            mAwayNameText.setText(mCursor.getString(COLUMN_INDEX_AWAY_NAME));
            mHomeGoalsText.setText(mCursor.getString(COLUMN_INDEX_HOME_GOALS));
            mAwayGoalsText.setText(mCursor.getString(COLUMN_INDEX_AWAY_GOALS));
            if(mCursor.getString(COLUMN_INDEX_ATTENDANCE) == null)
            	mExtraFlipper.removeView(mAttendanceText);
            else
            	mAttendanceText.setText("Attendance: " + mCursor.getString(COLUMN_INDEX_ATTENDANCE));
            //mExtraFlipper.addView(mAttendanceText);
			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
				Date d = df.parse(mCursor.getString(COLUMN_INDEX_DATE));
				String date = DateUtils.formatDate(d, "EEEE, d MMMM");
	            mDateText.setText(date);
	            //mExtraFlipper.addView(mDateText);
			} catch (ParseException e) {
				mExtraFlipper.removeView(mDateText);
			}
            
        } else {
        	mTimeChrono.setVisibility(View.GONE);
            mHomeNameText.setVisibility(View.GONE);
            mAwayNameText.setVisibility(View.GONE);
            mHomeGoalsText.setVisibility(View.GONE);
            mAwayGoalsText.setVisibility(View.GONE);
            mHomeScorersText.setVisibility(View.GONE);
            mAwayScorersText.setVisibility(View.GONE);
            mAttendanceText.setText(getText(R.string.error_match_notfound));
        }
    }
	@Override
	public void onDestroy(){
		super.onDestroy();
		//getContentResolver().unregisterContentObserver(mObserver);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt("EXTRA_FLIPPER_INDEX", mExtraFlipper.getDisplayedChild());
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		int i = savedInstanceState.getInt("EXTRA_FLIPPER_INDEX");
		if(i < mExtraFlipper.getChildCount()) mExtraFlipper.setDisplayedChild(i);
		super.onRestoreInstanceState(savedInstanceState);
	}
	
	private long parseDate(String date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
		try {
			Date d = df.parse(mDate);
			return d.getTime();
		}catch (Exception e){
			return 0;
		}
	}
	@Override
	public void onClick(View v) {
		float midX = v.getWidth() / 2;
		float midY = v.getHeight() / 2;
		ScaleAnimation sa = new ScaleAnimation(1f, 1.1f, 1f, 1.1f, midX, midY);
		sa.setDuration(250);
		v.startAnimation(sa);
		sa = new ScaleAnimation(1.1f, 1f, 1.1f, 1f, midX, midY);
		sa.setDuration(250);
		v.startAnimation(sa);
		if(v == mHomeNameText){
	        Uri uri = Uri.withAppendedPath(Provider.Teams.CONTENT_URI, mHomeUuid);
	        startActivity(new Intent(Intent.ACTION_VIEW, uri));
		}else if(v == mAwayNameText){
	        Uri uri = Uri.withAppendedPath(Provider.Teams.CONTENT_URI, mAwayUuid);
	        startActivity(new Intent(Intent.ACTION_VIEW, uri));
		}
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			flipperX = event.getX();
			break;
		case MotionEvent.ACTION_UP:
			// Get the X value when the user released his/her finger
            float currentX = event.getX();            

            // going backwards: pushing stuff to the right
            if (flipperX < currentX)
            {
            	if(mExtraFlipper.getDisplayedChild() != 0){
	                 // Set the animation
	                  //mExtraFlipper.setAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left));
	                  // Flip!
	                  mExtraFlipper.showPrevious();
            	}
            }

            // going forwards: pushing stuff to the left
            if (flipperX > currentX)
            {
            	if(mExtraFlipper.getDisplayedChild() != mExtraFlipper.getChildCount() - 1){
	                 // Set the animation
	                 //mExtraFlipper.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
	                  // Flip!
	                 mExtraFlipper.showNext();
            	}
            }
            break;
		}
		return true;
	}

}
